﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProcedureControlApi.DbContext;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace ProcedureControlApi.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ServerManagerController : ControllerBase
    {
        private static ProcessHelper _processHelper = new ProcessHelper(null, null, null);

        private readonly ILogger<ServerManagerController> _logger;

        public ServerManagerController(ILogger<ServerManagerController> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<Server> GetServers()
        {
            using (var db = new ProcedureServerContext())
            {
                return db.Servers.ToList();
            }
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> AddServer([FromBody] Server server)
        {
            using (var db = new ProcedureServerContext())
            {
                var isExit = db.Servers.Any(e => e.Name == server.Name);
                if (isExit)
                {
                    return "error";
                }
                server.CreateTime = DateTime.Now;
                server.IsDelete = false;
                server.IsOnline = false;
                await db.Servers.AddAsync(server);
                await db.SaveChangesAsync();
                return "ok";
            }
        }
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<string> UpdateServer([FromBody] Server server)
        {
            using (var db = new ProcedureServerContext())
            {
                var isExit = db.Servers.Any(e => e.Name == server.Name);
                if (isExit)
                {
                    return "error";
                }
                db.Servers.Update(server);
                await db.SaveChangesAsync();
                return "ok";
            }
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{id:int}")]
        public async Task<string> DelServer(int id)
        {
            using (var db = new ProcedureServerContext())
            {
                var data = db.Servers.Where(e => e.Id == id).FirstOrDefault();
                if (data != null && data.Id > 0)
                {
                    return "error";
                }
                data.IsDelete = true;
                db.Servers.Update(data);
                await db.SaveChangesAsync();
                return "ok";
            }
        }

        /// <summary>
        /// 服务启动和停止
        /// </summary>
        /// <param name="serverName"></param>
        /// <param name="serverType"></param>
        /// <param name="controlType"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("{serverName}/{serverType:int}/{controlType:int}")]
        public ResponseMesage Control(string serverName, ServerTypeEnum serverType, ControlTypeEnum controlType)
        {
            ResponseMesage responseMesage = new ResponseMesage
            {
                ResultCode = 400,
            };
            if (string.IsNullOrEmpty(serverName))
            {
                responseMesage.Message = "serverName 不能为空";
                return responseMesage;
            }
            ProcessHelper.KillProcess(filePath:CmdHelper.filePath);
            switch (serverType)
            {
                case ServerTypeEnum.service:
                    switch (controlType)
                    {
                        case ControlTypeEnum.Start:
                            responseMesage= CmdHanle(serverName, CmdHelper.windowsStartServerCmd);
                            break;
                        case ControlTypeEnum.Stop:
                            responseMesage= CmdHanle(serverName,CmdHelper.windowsStopServerCmd);
                            break;
                        case ControlTypeEnum.Restart:
                            responseMesage=CmdHanle(serverName, CmdHelper.windowsRestartServerCmd);
                            break;
                        default:
                            responseMesage.Message = $"不存在此操作类型{controlType}";
                            break;
                    }
                    return responseMesage;
                case ServerTypeEnum.website:
                    switch (controlType)
                    {
                        case ControlTypeEnum.Start:
                            responseMesage = CmdHanle(serverName, CmdHelper.iisWebSiteStartServerCmd);
                            break;
                        case ControlTypeEnum.Stop:
                            responseMesage = CmdHanle(serverName, CmdHelper.iisWebSiteStopServerCmd);
                            break;
                        case ControlTypeEnum.Restart:
                            responseMesage.Message = $"iiswebsite不存在此重启前调用关闭然后调用启动";
                            break;
                        default:
                            responseMesage.Message = $"不存在此操作类型{controlType}";
                            break;
                    }
                    return responseMesage;
                default:
                    responseMesage.Message = $"不存在此类型的服务{serverType}";
                    return responseMesage;
            }
        }

        private static ResponseMesage CmdHanle(string serverName,string cmd)
        {
            ResponseMesage responseMesage = new ResponseMesage();
            if (_processHelper.RunProcess(CmdHelper.filePath, string.Format(cmd, serverName), out var  output, out var error))
            {
                responseMesage.Error = error;
                responseMesage.Data = output;
                responseMesage.Message = $"正常处理命令";
                responseMesage.ResultCode = 200;
                return responseMesage;
            }
            else
            {
                responseMesage.Error = error;
                responseMesage.Data = output;
                responseMesage.Message = $"处理命令:{CmdHelper.windowsStartServerCmd}失败";
                responseMesage.ResultCode = 500;
                return responseMesage;
            }
        }
    }
    /// <summary>
    /// 命令
    /// </summary>
    public enum ControlTypeEnum
    {
        Start = 0,
        Stop = 1,
        Restart = 2
    }
}
